// pages/insurance/orderCreate/index.js
import components from './components.js'
import request from '../../../baseRequest'
import urls from '../../../requestUrl'

const {
    $Message
} = require('../../../components/base/index.js');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        insuranceType: '1',
        formType: '0',
        serviceList: [],
        currentServiceId: '',
        currentServicePrice: '',
        formComponentList1: components.type1,
        formComponentList2: components.type2,
        formComponentList3: components.type3,
        showSpin: true,
        showSpin2: false,
        currentCarId: '',
        orderPrice: 0,
        orderNum: 1,
        effectiveTime: '24小时',
        effectiveHour: 0,
        globalAuthType: 1,
        authType: 1
    },

    /**处理切换服务类型 */
    handleChangeService(e) {
        console.log(e)
        let id = e.detail.value
        let p = this.data.serviceList.find((item) => item.id === id)
        if (p) {
            this.setData({
                effectiveHour: p.effectiveHour,
                currentServiceId: id,
                orderPrice: p.price,
                currentServicePrice: this.data.orderType === '0' ? '0.00' : (p.price * this.getTrueDays(this.data.orderNum).value).toFixed(2),
                uploadType: this.getUploadType(p)
            })
        }
    },

    /**切换作业车牌 */
    handleChangeCarNum(e) {
        let id = e.detail.value
            // console.log('carid', id)
        this.setData({
            currentCarId: id
        })
    },

    /**获取图片上传约束方式 */
    getUploadType(service) {
        let target = []
        let t = service.uploadType
        if (t.is_photo === '1') {
            target.push('album')
        }
        if (t.is_taking_pictures === '1') {
            target.push('camera')
        }
        return target
    },

    /**隐藏Spin */
    hiddenSpinItem() {
        setTimeout(() => {
            this.setData({
                showSpin: false
            })
        }, 1000)
    },

    /**获取服务类型列表 */
    getServiceListByType(insuranceType) {
        let param = {
            "insuranceType": this.data.insuranceType,
            "openid": this.data.openid
        }

        request.postRequest(urls.insurance.initOrder, param, (res) => {
                let d = {}
                if (res.buyerInfo) {
                    d = {
                        ['formComponentList1[3].value']: res.buyerInfo.buyerName,
                        ['formComponentList1[4].value']: res.buyerInfo.buyerTelphone,
                        ['formComponentList2[2].value']: res.buyerInfo.buyerName,
                        ['formComponentList2[3].value']: res.buyerInfo.buyerTelphone,
                        ['formComponentList2[2].disabled']: !!res.buyerInfo.buyerName,
                        ['formComponentList2[3].disabled']: !!res.buyerInfo.buyerName,
                        ['formComponentList3[5].value']: res.buyerInfo.buyerName,
                        ['formComponentList3[6].value']: res.buyerInfo.buyerTelphone,
                        ['formComponentList3[7].value']: res.buyerInfo.emergencyContactPerson || '',
                        ['formComponentList3[8].value']: res.buyerInfo.emergencyContactNumber || '',
                        ['formComponentList3[0].files']: res.buyerInfo.idCardFrontImgUrl ? [{
                            url: '/' + res.buyerInfo.idCardFrontImgUrl.split('.com/')[1],
                            baseUrl: res.buyerInfo.idCardFrontImgUrl.split('.com/')[0] + '.com',
                            status: 'success',
                            id: '',
                        }] : [],
                        ['formComponentList3[1].files']: res.buyerInfo.idCardBackImgUrl ? [{
                            url: '/' + res.buyerInfo.idCardBackImgUrl.split('.com/')[1],
                            baseUrl: res.buyerInfo.idCardBackImgUrl.split('.com/')[0] + '.com',
                            status: 'success',
                            id: '',
                        }] : []
                    }
                }
                d.serviceList = res.serviceList
                d.currentServiceId = this.data.currentServiceId || ''
                d.carList = res.carInfo.carNum.map((item) => {
                    return { 'id': item.id, 'name': item.rescueCarNum }
                })
                d.currentCarId = res.carInfo.currentCarId
                this.setData(d)
                this.hiddenSpinItem()
            },
            () => {})
    },

    /**处理上传组件回掉 */
    completeCarNumberImgsUpload(e) {
        let detail = e.detail
        this.setData({
            ['formParam.carNumberImgs']: detail,
            ['formComponentList1[1].isUpload']: true
        })
    },
    completeCarFrontSideImgsUpload(e) {
        let detail = e.detail
        this.setData({
            ['formParam.carFrontSideImgs']: detail,
            ['formComponentList1[2].isUpload']: true
        })
    },
    completeCarBackSideImgsUpload(e) {
        let detail = e.detail
        this.setData({
            ['formParam.carBackSideImgs']: detail,
        })
        this.handelCreateInsuranceOrder()
    },
    completeUserLicenceImgsUpload(e) {
        let detail = e.detail
        this.setData({
            ['formParam.userLicenceImgs']: detail,
            ['formComponentList2[1].isUpload']: true
        })
    },
    completeUserCarImgsUpload(e) {
        let detail = e.detail
        console.log(detail)
        this.setData({
            ['formParam.userCarImgs']: detail
        })
        this.handelCreateInsuranceOrder()
    },
    completeIdCardFrontImgsUpload(e) {
        let detail = e.detail
        this.setData({
            ['formParam.idCardFrontImg']: detail,
            ['formComponentList3[1].isUpload']: true
        })
    },
    completeIdCardBackImgsUpload(e) {
        let detail = e.detail
        this.setData({
            ['formParam.idCardBackImg']: detail
        })
        this.handelCreateInsuranceOrder()
    },

    onBuyTypeChange(e) {
        console.log(e)
    },
    onBuyNumChange(e) {
        const num = parseInt(e.detail.value);
        const obj = this.getTrueDays(num);
        this.setData({
            orderNum: num,
            effectiveTime: obj.label,
            currentServicePrice: this.data.orderType === '0' ? '0.00' : (this.data.orderPrice * obj.value).toFixed(2)
        })
    },

    getTrueDays(type) {
        if (this.data.formType === '2') {
            if (type === 1) {
                return {
                    label: '24小时',
                    value: 1
                }
            } else if (type === 2) {
                return {
                    label: '7天',
                    value: 7
                }
            } else {
                const today = new Date();
                const date = new Date();
                date.setMonth(date.getMonth() + 1);
                const days = Math.round((date - today) / (24 * 60 * 60 * 1000));
                return {
                    label: `${days}天`,
                    value: days
                }
            }
        } else {
            return {
                label: (this.data.effectiveHour * type) + '小时',
                value: type
            }
        }
    },

    /**处理点击上传表单*/
    handleSubmitForm(e) {
        if (!this.data.currentServiceId) {
            this.showErrorMessage('请选择服务保障额度')
            return
        }
        let data = e.detail.value
        if (this.data.formType === '0' && this.checkForType1(data)) {
            this.setData({
                showSpin2: true,
                formParam: data,
                ['formComponentList1[0].isUpload']: true,
            })
        }
        if (this.data.formType === '1' && this.checkForType2(data)) {
            this.setData({
                showSpin2: true,
                formParam: data,
                ['formComponentList2[0].isUpload']: true,
            })
        }

        if (this.data.formType === '2' && this.checkForType3(data)) {
            const quantity = this.getTrueDays(this.data.orderNum).value
            this.setData({
                showSpin2: true,
                formParam: {
                    ...data,
                    quantity
                },
                ['formComponentList3[0].isUpload']: true,
            })
        }
        wx.pageScrollTo({
            scrollTop: 0,
        })
    },

    /**请求创建服务订单 */
    handelCreateInsuranceOrder() {
        let param = this.data.formParam
        param.openid = this.data.openid
        param.insuranceType = this.data.insuranceType
        param.currentServiceId = this.data.currentServiceId
        param.orderPrice = this.data.currentServicePrice
            //订单类型
        param.orderType = this.data.orderType
            //新增分销码参数
        param.distributeCode = this.data.distributeCode
        console.log('formParam', param)
        request.postRequest(urls.insurance.createOrder, param, (res) => {
            this.setData({
                showSpin2: false
            })
            let id = res.id
            wx.showToast({
                title: '订单创建成功'
            })
            let _url = this.data.orderType === '1' ? `/pages/insurance/orderPay/index?id=${id}` : `/pages/insurance/orderDetail/index?id=${id}`
            wx.redirectTo({
                url: _url
            })
        }, () => {})
    },

    /**校验表单信息1 */
    checkForType1(data) {
        //车架号图片
        if (data.carNumberImgs.length === 0) {
            this.showErrorMessage('请上传车牌或车架号图片')
            return false
        }
        //车前方45度图片
        if (data.carFrontSideImgs.length === 0) {
            this.showErrorMessage('请上传车前方45度图片')
            return false
        } else if (data.carFrontSideImgs.length < 1) {
            this.showErrorMessage('车前方45度图片不少于1张')
            return false
        }
        //车后方45度图片
        if (data.carBackSideImgs.length === 0) {
            this.showErrorMessage('请上传车后方45度图片')
            return false
        } else if (data.carBackSideImgs.length < 1) {
            this.showErrorMessage('车后方45度图片不少于1张')
            return false
        }
        //购买人
        if (!data.buyerName) {
            this.showErrorMessage('请填写购买人姓名')
            return false
        }
        //购买人电话
        if (!data.buyerTelphone) {
            this.showErrorMessage('请填写购买人电话')
            return false
        } else if (!this.checkTelphoneNumber(data.buyerTelphone)) {
            this.showErrorMessage('购买人电话格式有误，请重新输入')
            return false
        }
        return true
    },
    /**校验表单信息2 */
    checkForType2(data) {
        //身份证或驾驶证图片上传
        if (data.userLicenceImgs.length === 0) {
            this.showErrorMessage('请上传身份证或驾驶证图片')
            return false
        }
        //人与车合照图片
        if (data.userCarImgs.length === 0) {
            this.showErrorMessage('请上传人与车合照图片')
            return false
        } else if (data.userCarImgs.length < 1) {
            this.showErrorMessage('人与车合照图片不少于1张')
            return false
        }
        //乘客姓名
        if (!data.passengerName) {
            this.showErrorMessage('请填写乘客姓名')
            return false
        }
        //乘客电话
        if (!data.passengerTelphone) {
            this.showErrorMessage('请填写乘客电话')
            return false
        } else if (!this.checkTelphoneNumber(data.passengerTelphone)) {
            this.showErrorMessage('乘客电话格式有误，请重新输入')
            return false
        }

        if (!data.driverName) {
            this.showErrorMessage('请填写司机姓名')
            return false
        }
        if (!data.driverMobile) {
            this.showErrorMessage('请填写司机电话')
            return false
        } else if (!this.checkTelphoneNumber(data.driverMobile)) {
            this.showErrorMessage('司机电话格式有误，请重新输入')
            return false
        }

        return true
    },
    /**校验表单信息2 */
    checkForType3(data) {
        if (data.idCardFrontImg.length !== 1) {
            this.showErrorMessage('请上传身份证正面图片')
            return false
        }
        if (data.idCardBackImg.length !== 1) {
            this.showErrorMessage('请上传身份证反面图片')
            return false
        }
        //乘客电话
        if (data.emergencyContactNumber || data.emergencyContactPerson) {
            if ( !this.checkTelphoneNumber(data.emergencyContactNumber)) {
                this.showErrorMessage('紧急联系人电话格式有误，请重新输入')
                return false
            }
            if (!data.emergencyContactPerson) {
                this.showErrorMessage('紧急联系人姓名格式有误，请重新输入')
                return false
            }
        }
        return true
    },
    /**显示错误提示 */
    showErrorMessage(str) {
        $Message({
            content: str,
            type: 'error'
        });
    },
    /**手机号码校验 */
    checkTelphoneNumber(telphone) {
        // var reg = /^1[3|4|5|7|8][0-9]{9}$/; //验证规则
        var reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57]|19[0-9]|16[0-9])[0-9]{8}$/
        return reg.test(telphone);
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        let type = options.type //产品分类（0：货物 & 1：乘客)
        this.data.currentServiceId = options.serviceid
        let typeId = options.typeid //产品分类ID（货物&乘客）
        let orderType = options.otype || '1' //0：赠送；1：付费
        console.log('type', type)
        if (!type) {
            let pk = getApp().getInsuranceTypeKey(typeId)
            console.log('pk', pk)
            if (pk == 'hwx') {
                type = '0'
            }
            if (pk == 'ckx') {
                type = '1'
            }
            if (pk === 'sjx') {
                type= '2'
            }
            console.log('type', type)
        }
        const navTitle = {
            '0': '货物责任服务购买',
            '1': '乘客责任服务购买',
            '2': '司机责任服务购买'
        };
        wx.setNavigationBarTitle({
            title: navTitle[type] || '',
        });
        let insuranceType = typeId || getApp().globalData.insuranceTypes[type].id
        const authType = getApp().globalData.userInfo.authType
        let openid = getApp().getUserOpenid()
        this.setData({
            insuranceType,
            formType: type,
            openid,
            orderType,
            effectiveTime: type === '2' ? '24小时' : '12小时',
            globalAuthType: authType,
            authType
        })
        this.getServiceListByType(insuranceType)
            //获取全局分销码
        this.data.distributeCode = getApp().getDistributeCode()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    // onShareAppMessage: function() {

    // }
})
